package com.zhuangjie.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaungjie.base.utils.PropertiesCopyUtils.PropertiesCopy;
import com.zhuangjie.security.provider.UserProvider;
import com.zhuangjie.shop.dto.ShopEvaluateDTO;
import com.zhuangjie.shop.entity.ShopDishEvaluate;
import com.zhuangjie.shop.entity.ShopEvaluate;
import com.zhuangjie.shop.mapper.ShopEvaluateMapper;
import com.zhuangjie.shop.service.ShopDishEvaluateService;
import com.zhuangjie.shop.service.ShopEvaluateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 店铺评价 服务实现类
 * </p>
 *
 * @author zhuangjie
 * @since 2024-04-25
 */
@Service
public class ShopEvaluateServiceImpl extends ServiceImpl<ShopEvaluateMapper, ShopEvaluate> implements ShopEvaluateService {

    @Autowired
    private ShopDishEvaluateService shopDishEvaluateService;

    @Override
    public void submitShopEvaluate(ShopEvaluateDTO shopEvaluateDTO) {
        ShopEvaluate shopEvaluate = PropertiesCopy.type(ShopEvaluateDTO.class, ShopEvaluate.class).produce(shopEvaluateDTO);
        // 设置额外需要参数（orderId->shopId）
        shopEvaluate.setUserId(UserProvider.currentUserId());
        // 保存
        boolean isSaveSuccess = this.save(shopEvaluate);
        Long shopEvaluateId = shopEvaluate.getId();
        if (!isSaveSuccess || shopEvaluateId == null) {
            throw new RuntimeException("提交到商家评价失败");
        }
        List<ShopEvaluateDTO.ShopDishEvaluate> shopDishEvaluateList = shopEvaluateDTO.getShopDishEvaluateList();
        if (shopDishEvaluateList != null && !shopDishEvaluateList.isEmpty()) {
            // 有订单菜品评价信息保存
            List<ShopDishEvaluate> shopDishEvaluates = PropertiesCopy.type(ShopEvaluateDTO.ShopDishEvaluate.class, ShopDishEvaluate.class)
                    .batchProduce(shopDishEvaluateList);
            shopDishEvaluates.forEach(shopDishEvaluate -> {
                shopDishEvaluate.setShopEvaluateId(shopEvaluateId);
                shopDishEvaluate.setShopId(shopEvaluateDTO.getShopId());
            });
            boolean isSaveDishEvaluateSuccess = shopDishEvaluateService.saveBatch(shopDishEvaluates);
            if (!isSaveDishEvaluateSuccess) {
                throw new RuntimeException("提交到商家评价菜品失败");
            }
        }
    }
}
